const base1 = 'http://58.241.230.210:9081';

export const uploadFile = (url, filePath, data) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: base1 + url,
      filePath,
      name: data.name || 'file',
      formData: data.formData || {},
      success: (res) => {
        const result = JSON.parse(res.data);
        console.log(`uploadFile filePath: %s, data: %o, res: %o`, filePath, data, result);
        resolve(result);
      },
      fail: (err) => {
        console.err(`uploadFile err: %o`, err);
        reject(err);
      },
    });
  });
};

export const downloadFile = (url) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const request = (url, data, method = 'POST', contentType = 'application/json') => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      data,
      method,
      header: {
        'content-type': contentType,
      },
      success: (res) => {
        console.log(`request req: %o, url: %s, res: %o`, data, url, res.data);
        resolve(res.data);
      },
      fail: (err) => {
        console.error(`request err: %o`, err);
        reject(err);
      },
    });
  });
};

export default {
  post: (url, data) => {
    return request(url, data, 'POST');
  },

  postForm: (url, data) => {
    return request(url, data, 'POST', 'application/x-www-form-urlencoded');
  },

  get: (url, data) => {
    return request(url, data, 'GET');
  },
};
